<template>
  <el-row :gutter="10">
    <el-col :span="24" class="mb10" v-if="props.showToolbar">
      <el-button-group class="mr10" v-if="props.operations.length > 0">
        <el-button
          v-for="(button, index) in props.operations"
          :v-bind="button"
          :type="button.type"
          :icon="button.icon"
          @click="button.click"
          :key="index"
          >{{ button.label }}
        </el-button>
      </el-button-group>
      <slot name="operations"></slot>

      <div style="float: right" v-if="state.isShowButton">
        <!-- <el-button icon="elementUpload"></el-button> -->
        <el-button icon="elementDownload" @click="exportTable()"></el-button>
        <el-button icon="elementRefresh" @click="reload"></el-button>
        <el-popover
          placement="bottom"
          title="操作"
          :width="200"
          trigger="click"
        >
          <el-row :gutter="15">
            <el-col v-for="(item, index) in state.columns" :key="index">
              <el-checkbox v-model="state.columns[index].checked">{{
                item.label
              }}</el-checkbox>
            </el-col>
          </el-row>

          <template #reference>
            <el-button icon="elementOperation"></el-button>
          </template>
        </el-popover>
      </div>
    </el-col>
    <el-col :span="24">
      <el-table
        :data="state.data"
        v-model="modelValue"
        :border="props.border"
        @selection-change="proxy.$emit('selection-change', $event)"
        :empty-text="state.emptyText"
        @sort-change="_tableSortChange"
        :show-header="props.showHeader"
        :size="props.size"
        :stripe="props.stripe"
        :show-overflow-tooltip="false"
      >
        <el-table-column
          v-if="props.selection"
          type="selection"
          align="center"
        ></el-table-column>
        <el-table-column
          label="序号"
          width="60"
          align="center"
          v-if="props.order"
        >
          <template #default="scope">
            <span
              >{{
                scope.$index + (state.param.page - 1) * state.param.limit + 1
              }}
            </span>
          </template>
        </el-table-column>
        <template v-for="(item, index) in state.columns" :key="item.id">
          <el-table-column
            v-if="item.checked"
            :type="item.type"
            :prop="item.prop"
            :label="item.label"
            :align="item.align"
            :width="item.width"
            :min-width="item.minWidth"
            :sortable="item.sortable"
            :formatter="item.formatter"
            :show-overflow-tooltip="item.tooltip"
          >
            <template #default="scope">
              <span v-if="item.formatter">{{ item.formatter(scope.row) }}</span>
              <slot
                v-else-if="item.slot"
                :name="item.slot"
                :row="scope.row"
                :index="scope.$index"
              />
              <span v-else>{{ scope.row[item.prop] }}</span>
            </template>
          </el-table-column>
        </template>
      </el-table>
      <template v-if="state.isPage">
        <el-pagination
          @size-change="onHandleSizeChange"
          @current-change="onHandleCurrentChange"
          class="mt15"
          :pager-count="5"
          :page-sizes="state.pageSizes"
          v-model:current-page="state.param.page"
          background
          v-model:page-size="state.param.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="state.param.count"
        >
        </el-pagination>
      </template>
    </el-col>
  </el-row>
</template>
<script lang="ts" setup>
import {
  unref,
  ref,
  getCurrentInstance,
  onMounted,
  toRefs,
  reactive,
  defineProps,
  defineExpose,
  defineEmits,
} from "vue";
import request from "/@/utils/request";
import { Local } from "/@/utils/storage";

const { proxy }: any = getCurrentInstance();

const props = defineProps({
  url: String,
  // 数据列表
  data: {
    type: Array,
    default: [],
  },
  // 需要展示的列 === prop：列数据对应的属性，label：列名，align：对齐方式，width：列宽, // table 表格的控制参数
  columns: {
    type: Array,
    default: [],
  },
  showToolbar: {
    type: Boolean,
    default: true,
  },
  isShowButton: {
    type: Boolean,
    default: false,
  },
  //操作按钮
  operations: {
    type: Array,
    default: [],
  },

  //查询条件
  where: {
    type: Object,
    default: {},
  },
  //是否分页
  isPage: {
    type: Boolean,
    default: true,
  },
  //是否加载
  isLoading: {
    type: Boolean,
    default: false,
  },
  //是否在表尾显示合计行
  isShowSummary: {
    type: Boolean,
    default: false,
    require: false,
  },
  //emptyText
  emptyText: {
    type: String,
    default: "暂无数据",
    require: false,
  },
  //是否带边框
  border: {
    type: Boolean,
    default: true,
  },
  //是否开启多选
  selection: {
    type: Boolean,
    default: false,
  },
  //序号

  order: {
    type: Boolean,
    default: false,
  },
  stripe: {
    type: Boolean,
    default: false,
  },
  //选择方式（仅用于多选时）
  type: {
    type: String,
    default: "select", //select：多选    radio：单选
    require: false,
  },
  //选择方式（仅用于多选时）
  size: {
    type: String,
    default: "", //select：多选    radio：单选
    require: false,
  },
  param: {
    page: 1,
    limit: 10,
    count: 10,
  },
  showHeader: {
    type: Boolean,
    default: true,
  },

  page: 0,
  modelValue: String,
});

const state = reactive({
  data: [],

  param: {
    queryJson: "",
    page: 1,
    limit: 10,
    count: 0,
  },
  isPage: true,
  isLoading: true,
  columns: [] as Array<Object>,
  operations: [] as Array<Object>,
  emptyText: "",
  pageSizes: [10, 20, 50, 100],
  isShowButton: false,
});

const _tableInit = () => {
  state.isPage = props.isPage;
  state.isShowButton = props.isShowButton;
  _columnInit();
  load();
};
//加载数据
const load = () => {
  state.isLoading = true;
  // state.emptyText = "加载中，请稍后...";
  state.data = props.data;
  state.param.queryJson = JSON.stringify(props.where);

  if (!proxy.$wigem.isEmpty(props.url)) {
    request({
      url: props.url,
      method: "get",
      params: state.param,
    })
      .then((res) => {
        if (res.code == 0) {
          state.data = res.data;
          if (state.isPage) {
            state.param.count = res.count;
          }
        }
        state.emptyText = "暂无数据";
        setTimeout(() => {
          state.isLoading = false;
        }, 400);
      })
      .catch((error) => {
        proxy.$wigem.log("表格数据加载失败...");
        state.emptyText = "暂无数据";
        state.isLoading = false;
      });
  } else {
    state.data = props.data;
  }
};

/**
 * @name 导出表格数据
 */

const exportTable = (name?: String): void => {
  debugger;
  if (state.isPage) {
    state.param.page = 1;
    state.param.limit = state.param.count;
  }
  let elementPlusTable = {
    tableName: name || "elementTable",
    url: props.url,
    isPage: props.isPage,
    cols: props.columns,
    queryJson: state.param.queryJson,
    page: state.param.page,
    limit: state.param.limit,
  };
  elementPlusTable.url = elementPlusTable.url.replace("api", "");

  request({
    url: "/api/excel/export/table",
    method: "post",
    data: elementPlusTable,
    responseType: "blob",
  }).then((res) => {
    let url = window.URL.createObjectURL(
      new Blob([res], { type: "application/vnd.ms-excel" })
    );
    let link = document.createElement("a");
    link.style.display = "none";
    link.href = url;
    link.setAttribute("download", elementPlusTable.tableName + ".xlsx");
    document.body.appendChild(link);
    link.click();
  });
};

const init = () => {
  _tableInit();
};

//重新加载
const reload = () => {
  debugger
  if (!state.isLoading) {
    state.isLoading = false;
    load();
  }
};
//获取全部选择数据
const getCheckData = () => {};

// 分页改变
const onHandleSizeChange = (val: number) => {
  state.param.limit = val;
  load();
};
// 分页改变
const onHandleCurrentChange = (val: number) => {
  state.param.page = val;
  load();
};

//选择改变时
const selectionChange = (selection) => {
  proxy.$emit("selection-change", selection);
};
//字段初始化
const _columnInit = () => {
  state.columns = [];
  props.columns.forEach((item: Object, index: Number) => {
    let dfop: Object = {
      headerAlign: "center",
      align: "center",
      label: "",
      prop: "",
      dictionaryCode: "",
      type: "",
      width: null,
      //固定列
      fixed: false,
      //是否开启排序
      sortable: false,
      //格式化
      formatter: false,
      //插槽名称
      slot: false,
      //最小宽度
      minWidth: "",
      //超出宽度显示提示
      tooltip: true,
      checked: true,
      children: [],
    };
    Object.assign(dfop, item);

    if (!!dfop.dictionaryCode) {
      dfop.formatter = (row, column) => {
        let dictionaryAllData = Local.get("dictionaryData");
        let data: Object = dictionaryAllData[dfop.dictionaryCode];
        let obj: Object = {};
        for (let key in data) {
          obj[data[key]["value"]] = data[key]["text"];
        }
        return obj[row[dfop.prop]];
      };
    }

    state.columns.push(dfop);
  });
};

const _tableSortChange = (sortOption) => {};

defineEmits();

_tableInit();

defineExpose({
  load,
  reload,
  init,
  export: exportTable,
});
</script>